package main

import (
	"fmt"
	"os"

	"github.com/sniperHW/kendynet"
	"github.com/tealeg/xlsx"
)

func eliminate(str string, e string) string {
	str_ := []byte(str)
	e_ := []byte(e)
	out := []byte{}

	f := func(c byte) bool {
		for _, v := range e_ {
			if c == v {
				return false
			}
		}
		return true
	}

	for _, v := range str_ {
		if f(v) {
			out = append(out, v)
		}
	}
	return string(out)
}

func main() {
	xlFile, err := xlsx.OpenFile("../GlobalConstData.xlsx")
	if err != nil {
		panic(err)
	}

	sheet := xlFile.Sheets[0]
	row0 := sheet.Rows[0]
	row1 := sheet.Rows[1]
	row2 := sheet.Rows[2]
	row3 := sheet.Rows[3]

	str :=
		`//默认配置
package GlobalConstData

const(
`

	for i, _ := range row0.Cells {
		type_ := row0.Cells[i].String()
		name := row1.Cells[i].String()
		desc := row2.Cells[i].String()
		if type_ == "string" {
			value := row3.Cells[i].String()
			str = str + fmt.Sprintf(`	%s = "%s" //%s`, name, value, eliminate(desc, "\n")) + "\n"
		} else if type_ == "int" {
			value, _ := row3.Cells[i].Int()
			str = str + fmt.Sprintf(`	%s = %d //%s`, name, value, eliminate(desc, "\n")) + "\n"
		} else if type_ == "bool" {
			value := row3.Cells[i].Bool()
			str = str + fmt.Sprintf(`	%s = %v //%s`, name, value, eliminate(desc, "\n")) + "\n"
		} else if type_ == "float" {
			value, _ := row3.Cells[i].Float()
			str = str + fmt.Sprintf(`	%s = %f //%s`, name, value, eliminate(desc, "\n")) + "\n"
		}
	}
	str = str + ")\n"

	out_path := "../../../../common/GlobalConstData/GlobalConstData.go"

	f, err := os.OpenFile(out_path, os.O_RDWR, os.ModePerm)
	if err != nil {
		if os.IsNotExist(err) {
			f, err = os.Create(out_path)
			if err != nil {
				kendynet.Errorf("create %s failed:%s", out_path, err.Error())
				return
			}
		} else {
			kendynet.Errorf("open %s failed:%s", out_path, err.Error())
			return
		}
	}

	err = os.Truncate(out_path, 0)

	_, err = f.WriteString(str)

	if nil != err {
		kendynet.Errorf("%s Write error:%s\n", out_path, err.Error())
	} else {
		kendynet.Infof("%s Write ok\n", out_path)
	}

	f.Close()
}
